package com.shop2cn.iapi.agentproducts.testcase;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.http.client.ClientProtocolException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.shop2cn.iapi.agentproducts.parameter.AddAgentProductBean;
import com.shop2cn.iapi.agentproducts.parameter.ImportAgentProductBean;
import com.shop2cn.iapi.agentproducts.parameter.ProductListDto;
import com.shop2cn.iapi.agentproducts.parameter.UpdateMarkupConfigBean;
import com.shop2cn.iapi.agentproducts.service.UpdateMarkupConfigCall;
import com.ymatou.iapi.godmch.parameter.CreateCodeBean;
import com.ymatou.iapi.godmch.parameter.SetMarkupConfigBean;
import com.ymatou.iapi.godmch.service.CreateCodeCall;
import com.ymatou.iapi.godmch.service.SetMarkupConfigCall;
import com.ymatou.iapi.prodstock.parameter.AgentProductPo;
import com.ymatou.mq.admin.parameter.MessageListBean;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.*;
import com.ymt.utils.tag.*;
import com.ymttest.business.service.AddAgentProductCallService;
import com.ymttest.business.service.MqQueryCallService;
import com.ymttest.business.service.shenqi.GodmchManageCallService;
import com.ymttest.database.sqlwapper.YmtProductsIWapper;

/**
 * 更改加价配置（商户回调）Test FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_UpdateMarkupConfig {
	private static UpdateMarkupConfigBean updatemarkupconfigBean;
	private static UpdateMarkupConfigCall updatemarkupconfigCall;
	private static YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();

	// 添加修改的场景需要包含在godmch发送总线消息case中
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("更改加价配置（商户回调）Test");
	}

	@Before
	public void caseUp() {
		updatemarkupconfigBean = new UpdateMarkupConfigBean();
		updatemarkupconfigCall = new UpdateMarkupConfigCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(updatemarkupconfigCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	/**
	 * 初始化SetMarkupConfigBean
	 * 
	 * @param agentUserId
	 * @param rootUserId
	 * @return
	 */
	private SetMarkupConfigBean initSetMarkupConfigBean(Integer agentUserId, Integer rootUserId) {
		SetMarkupConfigBean setmarkupconfigBean = new SetMarkupConfigBean();
		setmarkupconfigBean.setAgentId(agentUserId);
		setmarkupconfigBean.setSupplierId(Arrays.asList(rootUserId));
		setmarkupconfigBean.setMarkupType(1);
		setmarkupconfigBean.setPercentage(new BigDecimal(10));
		setmarkupconfigBean.setDecimalType(1);
		setmarkupconfigBean.setOnSaleType(1);
		setmarkupconfigBean.setRefreshProduct(true);
		return setmarkupconfigBean;
	}

	/**
	 * 调用
	 * 
	 * @param setmarkupconfigBean
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	private void SetMarkupConfig(SetMarkupConfigBean setmarkupconfigBean) throws ClientProtocolException, IOException {
		SetMarkupConfigCall setmarkupconfigCall = new SetMarkupConfigCall();
		setmarkupconfigCall.setData(setmarkupconfigBean);
		setmarkupconfigCall.callService();
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_UpdateMarkupConfig_001() {
		Logger.start(true, "删除加价配置时设置商品自己加价标记为0");
		try {
			Integer rootUserId = GodmchManageCallService.CreateGodMch();
            Integer agenttype=GodmchManageCallService.getAgentType(rootUserId, 1);
            Integer agentUserId = GodmchManageCallService.getAgentMchId(rootUserId, agenttype);
            
			// 设置自动加价配置
			SetMarkupConfigBean setmarkupconfigBean = initSetMarkupConfigBean(agentUserId, rootUserId);
			setmarkupconfigBean.setDecimalType(1);
			setmarkupconfigBean.setPercentage(new BigDecimal(10));
			SetMarkupConfig(setmarkupconfigBean);
			// 创建单规格商品
			AddAgentProductBean addAgentProductBean = AddAgentProductCallService.initAddAgentProduct(rootUserId,
					"autotest", true);
			while (addAgentProductBean.getCatalogList().size() > 1) {
				addAgentProductBean.getCatalogList().remove(0);
			}
			// 设置拿货价 这里的代理所属agenttype默认和第一个关联 所以设置第一个价格
			addAgentProductBean.getCatalogList().get(0).getAgentPriceList().get(0).setAgentPrice(10);
			Logger.debug("addAgentProductBean:" + FormatUtil.beanToGSONString(addAgentProductBean));
			String productId = AddAgentProductCallService.AddAgentProduct(addAgentProductBean);
			Thread.sleep(5000);
			
			// 查询总线发送自动导入商品消息
			MessageListBean MessageListBean = MqQueryCallService.initImportAgentproduct(productId, rootUserId);
			List<Map> joa = MqQueryCallService.GetMqMessage(MessageListBean);
			if (joa.size() == 0) {
				Thread.sleep(5000);
				joa = MqQueryCallService.GetMqMessage(MessageListBean);
			}
			joa.forEach(ele -> {
				Logger.debug(ele.toString());
			});
			// 查询自动导入的商品的信息
			List<AgentProductPo> ap = ymtProductsIWapper.selectAgentProductByRootProductId(productId).stream()
					.filter(x -> x.getAction() == 0).filter(x -> x.getUserId() == agentUserId)
					.collect(Collectors.toList());
			Logger.debug("ap:" + FormatUtil.beanToGSONString(ap));
			Logger.verifyEquals(true, ap.get(0).getAutoMarkup(), "验证isAutoMarkup");
			updatemarkupconfigBean.setAgentId(agentUserId);
			updatemarkupconfigBean.setOperateType(3);
			updatemarkupconfigBean.setSupplierId(rootUserId);
			updatemarkupconfigCall.setData(updatemarkupconfigBean);
			updatemarkupconfigCall.callService();
			Logger.verifyEquals("ok", updatemarkupconfigCall.getReturnData(), "验证code");
			Thread.sleep(5000);
			ap = ymtProductsIWapper.selectAgentProductByRootProductId(productId).stream()
					.filter(x -> x.getAction() == 0).filter(x -> x.getUserId() == agentUserId)
					.collect(Collectors.toList());
			Logger.debug("ap:" + FormatUtil.beanToGSONString(ap));
			
			// ymtProductsIWapper.updateAgentProductAutoMarkup(ap.get(0).getProductId(),
			// true);
			// ap =
			// ymtProductsIWapper.selectAgentProductByRootProductId(productId).stream().filter(x
			// -> x.getAction() == 0)
			// .filter(x -> x.getUserId() ==
			// agentUserId).collect(Collectors.toList());
			// Logger.debug("ap:" + FormatUtil.beanToGSONString(ap));
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_UpdateMarkupConfig_002() {
		Logger.start(true, "新增加价配置时勾选覆盖--回调更改加价配置--回调更新价格--人如果勾选自动上架就回调自动导入");
		// 渠道商十个商品，代理商手动导入五个商品 自动覆盖以及自动上架后，代理商十个商品，并且自动改价
		try {
			Integer rootUserId = GodmchManageCallService.CreateGodMch();
            Integer agenttype=GodmchManageCallService.getAgentType(rootUserId, 1);
            Integer agentUserId = GodmchManageCallService.getAgentMchId(rootUserId, agenttype);
            
			List<String> rootProds = new ArrayList<>();
			List<String> agentProds = new ArrayList<>();
			List<String> immportProds = new ArrayList<>();
			
			// 渠道商十个商品，代理商手动导入五个商品
			for (int i = 0; i < 5; i++) {
				AddAgentProductBean addAgentProductBean1 = AddAgentProductCallService.initAddAgentProduct(rootUserId,
						"", true);
				String productId1 = AddAgentProductCallService.AddAgentProduct(addAgentProductBean1);
				// 渠道商和等待导入的
				rootProds.add(productId1);
				immportProds.add(productId1);
				AddAgentProductBean addAgentProductBean = AddAgentProductCallService.initAddAgentProduct(rootUserId, "",
						true);
				String productId = AddAgentProductCallService.AddAgentProduct(addAgentProductBean);
				rootProds.add(productId);
				ImportAgentProductBean importAgentProductBean = AddAgentProductCallService
						.initImportAgentProduct(agentUserId, "", productId, rootUserId, false);
				String agentProductId = AddAgentProductCallService.ImportAgentProduct(importAgentProductBean);
				agentProds.add(agentProductId);
			}

			Thread.sleep(5000);
			// 设置自动加价配置
			SetMarkupConfigBean setmarkupconfigBean = initSetMarkupConfigBean(agentUserId, rootUserId);
			setmarkupconfigBean.setPercentage(new BigDecimal(33));
			SetMarkupConfig(setmarkupconfigBean);

			
			// 查询总线发送更改加价配置--一条修改配置的回调
			MessageListBean markupconfig = MqQueryCallService.initSetMarkupConfig(agentUserId, rootUserId);
			List<Map> mjoa = MqQueryCallService.GetMqMessage(markupconfig);
			if (mjoa.size() == 0) {
				Thread.sleep(5000);
				mjoa = MqQueryCallService.GetMqMessage(markupconfig);
			}
			
			mjoa.forEach(ele -> {
				Logger.debug(ele.toString());
			});
			Logger.verifyEquals(mjoa.size(), 1, "回调了改价" + markupconfig.toString());
			// 查询总线发送自动导入商品消息--五条等待导入的
			immportProds.forEach(b -> {
				try {
					MessageListBean MessageListBean = MqQueryCallService.initImportAgentproduct(b, agentUserId);
					List<Map> joa = MqQueryCallService.GetMqMessage(MessageListBean);
					if (joa.size() == 0) {
						Thread.sleep(5000);
						joa = MqQueryCallService.GetMqMessage(MessageListBean);
					}
					joa.forEach(ele -> {
						Logger.debug(ele.toString());
					});
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			});
			// 查询总线发送改更改老价格的回调--五条修改价格的回调
			agentProds.forEach(b -> {
				try {
					MessageListBean markup = MqQueryCallService.initSyncAutoMarkup(b, agentUserId);
					List<Map> jmarkup = MqQueryCallService.GetMqMessage(markup);
					if (jmarkup.size() == 0) {
						Thread.sleep(5000);
						jmarkup = MqQueryCallService.GetMqMessage(markup);
					}
					jmarkup.forEach(ele -> {
						Logger.debug(ele.toString());
					});
					Logger.verifyEquals(jmarkup.size(), 1, "修改价格回调" + markup.toString());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			});

			List<ProductListDto> getProductLists2 = AddAgentProductCallService.GetProductLists(agentUserId);
			if (getProductLists2.size() != 10) {
				Thread.sleep(10000);
				getProductLists2 = AddAgentProductCallService.GetProductLists(agentUserId);
			}
			
			// 查询自动导入的商品的价格
			Logger.verifyEquals(getProductLists2.size(), 10, "导入了十个商品");
			getProductLists2.forEach(b -> {
				Logger.verifyEquals(b.getAutoMarkupStatus(), 1, "有自动改价的标志");
				double agentprice = b.getCatalogList().get(0).getAgentPrice();
				// 代理价*0.2=直销价
				Logger.verifyEquals(new Long(Math.round(agentprice * 1.33)).intValue(),
						new Double(b.getCatalogList().get(0).getDirectPrice()).intValue(), "");
			});

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_UpdateMarkupConfig_003() {
		Logger.start(true, "新增加价配置时不覆盖--自动上架--回调更改加价配置--只会刷新新的商品--不会回调其他的更新价格商品");
		// 渠道商十个商品，代理商手动导入五个商品 选择自动上架不覆盖，新导入的商品会刷新，老商品不会刷新
		try {

			// 创建渠道商
			CreateCodeBean createAllMsgSellerMch = GodmchManageCallService.CreateAllMsgSellerMch();
			// 创建渠道商邀请码
			CreateCodeCall createCodeCall2 = GodmchManageCallService.createCodeCall(createAllMsgSellerMch);
			// 创建代理商
			Integer agentUserId = GodmchManageCallService.CreateSellerMch(
					createCodeCall2.getJsonObject().getAsJsonObject("result").get("code").getAsString());
			int rootUserId = createAllMsgSellerMch.getMchId();
			List<String> rootProds = new ArrayList<>();
			List<String> agentProds = new ArrayList<>();
			List<String> immportProds = new ArrayList<>();
			List<String> autoMarkupStatus = new ArrayList<>();
			// 渠道商十个商品，代理商手动导入五个商品
			for (int i = 0; i < 5; i++) {
				AddAgentProductBean addAgentProductBean1 = AddAgentProductCallService.initAddAgentProduct(rootUserId,
						"", true);
				String productId1 = AddAgentProductCallService.AddAgentProduct(addAgentProductBean1);
				// 渠道商和等待导入的
				rootProds.add(productId1);
				immportProds.add(productId1);
				AddAgentProductBean addAgentProductBean = AddAgentProductCallService.initAddAgentProduct(rootUserId, "",
						true);
				String productId = AddAgentProductCallService.AddAgentProduct(addAgentProductBean);
				rootProds.add(productId);
				ImportAgentProductBean importAgentProductBean = AddAgentProductCallService
						.initImportAgentProduct(agentUserId, "", productId, rootUserId, false);
				String agentProductId = AddAgentProductCallService.ImportAgentProduct(importAgentProductBean);
				agentProds.add(agentProductId);
			}

			// 设置自动加价配置
			SetMarkupConfigBean setmarkupconfigBean = initSetMarkupConfigBean(agentUserId, rootUserId);
			setmarkupconfigBean.setPercentage(new BigDecimal(33));
			setmarkupconfigBean.setRefreshProduct(false);
			SetMarkupConfig(setmarkupconfigBean);

			// 查询总线发送更改加价配置--一条修改配置的回调
			MessageListBean markupconfig = MqQueryCallService.initSetMarkupConfig(agentUserId, rootUserId);
			List<Map> mjoa = MqQueryCallService.GetMqMessage(markupconfig);
			if (mjoa.size() == 0) {
				Thread.sleep(5000);
				mjoa = MqQueryCallService.GetMqMessage(markupconfig);
			}
			mjoa.forEach(ele -> {
				Logger.debug(ele.toString());
			});
			Logger.verifyEquals(mjoa.size(), 1, "回调了改价");

			// 查询总线发送自动导入商品消息--五条等待导入的
			immportProds.forEach(b -> {
				try {
					MessageListBean MessageListBean = MqQueryCallService.initImportAgentproduct(b, agentUserId);
					List<Map> joa = MqQueryCallService.GetMqMessage(MessageListBean);
					if (joa.size() == 0) {
						Thread.sleep(5000);
						joa = MqQueryCallService.GetMqMessage(MessageListBean);
					}
					joa.forEach(ele -> {
						Logger.debug(ele.toString());
					});
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			});

			// 老商品不会价格回调
			agentProds.forEach(b -> {
				try {
					MessageListBean markup = MqQueryCallService.initSyncAutoMarkup(b, agentUserId);
					List<Map> jmarkup = MqQueryCallService.GetMqMessage(markup);
					if (jmarkup.size() == 0) {
						Thread.sleep(5000);
						jmarkup = MqQueryCallService.GetMqMessage(markup);
					}
					jmarkup.forEach(ele -> {
						Logger.debug(ele.toString());
					});
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			});

			// 查询自动导入的商品的价格
			List<ProductListDto> getProductLists2 = AddAgentProductCallService.GetProductLists(agentUserId);
			Logger.verifyEquals(getProductLists2.size(), 10, "老商品+新商品=十个");
			getProductLists2.forEach(b -> {
				if (agentProds.contains(b.getProductId())) {
					Logger.verifyEquals(b.getAutoMarkupStatus(), 0, "没有自动改价的标志");
					double agentprice = b.getCatalogList().get(0).getAgentPrice();
					// 代理价*0.2=直销价
					Logger.verifyNotEquals(new Long(Math.round(agentprice * 1.33)).intValue(),
							new Double(b.getCatalogList().get(0).getDirectPrice()).intValue(), "老商品没有自动改价格");
				} else {
					Logger.verifyEquals(b.getAutoMarkupStatus(), 1, "新导入的商品自动改价");
					double agentprice = b.getCatalogList().get(0).getAgentPrice();
					// 代理价*0.2=直销价
					Logger.verifyEquals(new Long(Math.round(agentprice * 1.33)).intValue(),
							new Double(b.getCatalogList().get(0).getDirectPrice()).intValue(), "新商品自动改价");
				}

			});

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_UpdateMarkupConfig_004() {
		Logger.start(true, "设置自动加价规则-2个供货商-发送两条总线消息");
		try {
			// 创建渠道商
			CreateCodeBean createAllMsgSellerMch = GodmchManageCallService.CreateAllMsgSellerMch();
			// 创建渠道商邀请码
			CreateCodeCall createCodeCall = GodmchManageCallService.createCodeCall(createAllMsgSellerMch);
			// 创建代理商
			Integer agentUserId = GodmchManageCallService.CreateSellerMch(
					createCodeCall.getJsonObject().getAsJsonObject("result").get("code").getAsString());
			int rootUserId1 = createAllMsgSellerMch.getMchId();
			// 创建渠道商2邀请码
			CreateCodeBean createAllMsgSellerMch1 = GodmchManageCallService.CreateAllMsgSellerMch();
			CreateCodeCall createCodeCall2 = GodmchManageCallService.createCodeCall(createAllMsgSellerMch1);
			Integer rootUserId2 = createAllMsgSellerMch1.getMchId();
			// 绑定
			GodmchManageCallService.InitbindmchBean(agentUserId, createCodeCall2.getCode());

			SetMarkupConfigBean initSetMarketupBean = GodmchManageCallService.initSetMarketupBean(agentUserId, Arrays.asList(rootUserId1,rootUserId2));
			SetMarkupConfigCall setMarketupBeanCall = GodmchManageCallService.SetMarketupBeanCall(initSetMarketupBean);

			Logger.comment("rootUserId1:" + rootUserId1);
			Logger.comment("rootUserId2:" + rootUserId2);
			Logger.comment("agentUserId:" + agentUserId);
			// 查询总线发送更改加价配置--一条修改配置的回调
			MessageListBean markupconfig = MqQueryCallService.initSetMarkupConfig(agentUserId, rootUserId1);
			List<Map> mjoa = MqQueryCallService.GetMqMessage(markupconfig);
			if (mjoa.size() == 0) {
				Thread.sleep(5000);
				mjoa = MqQueryCallService.GetMqMessage(markupconfig);
			}
			mjoa.forEach(ele -> {
				Logger.debug(ele.toString());
			});
			Logger.verifyEquals(mjoa.size(), 1, "回调了改价");

			// 查询总线发送更改加价配置--一条修改配置的回调
			MessageListBean markupconfig1 = MqQueryCallService.initSetMarkupConfig(agentUserId, rootUserId2);
			List<Map> mjoa1 = MqQueryCallService.GetMqMessage(markupconfig1);
			if (mjoa1.size() == 0) {
				Thread.sleep(5000);
				mjoa1 = MqQueryCallService.GetMqMessage(markupconfig1);
			}
			mjoa1.forEach(ele -> {
				Logger.debug(ele.toString());
			});
			Logger.verifyEquals(mjoa.size(), 1, "再次回调了改价");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_UpdateMarkupConfig_005() {
		Logger.start(true, "修改加价配置时设置商品自己加价标记为0");
		try {

			// 创建渠道商
			CreateCodeBean createAllMsgSellerMch = GodmchManageCallService.CreateAllMsgSellerMch();
			// 创建渠道商邀请码
			CreateCodeCall createCodeCall2 = GodmchManageCallService.createCodeCall(createAllMsgSellerMch);
			// 创建代理商
			Integer agentUserId = GodmchManageCallService.CreateSellerMch(
					createCodeCall2.getJsonObject().getAsJsonObject("result").get("code").getAsString());
			int rootUserId = createAllMsgSellerMch.getMchId();
			// 设置自动加价配置
			SetMarkupConfigBean setmarkupconfigBean = initSetMarkupConfigBean(agentUserId, rootUserId);
			setmarkupconfigBean.setDecimalType(1);
			setmarkupconfigBean.setMarkupType(3);
			setmarkupconfigBean.setPercentage(new BigDecimal(10));
			SetMarkupConfig(setmarkupconfigBean);
			// 创建单规格商品
			AddAgentProductBean addAgentProductBean = AddAgentProductCallService.initAddAgentProduct(rootUserId,
					"autotest", true);
			while (addAgentProductBean.getCatalogList().size() > 1) {
				addAgentProductBean.getCatalogList().remove(0);
			}
			// 设置拿货价 这里的代理所属agenttype默认和第一个关联 所以设置第一个价格
			addAgentProductBean.getCatalogList().get(0).getAgentPriceList().get(0).setAgentPrice(10);
			Logger.debug("addAgentProductBean:" + FormatUtil.beanToGSONString(addAgentProductBean));
			String productId = AddAgentProductCallService.AddAgentProduct(addAgentProductBean);
			// 查询总线发送自动导入商品消息
			MessageListBean MessageListBean = MqQueryCallService.initImportAgentproduct(productId, rootUserId);
			List<Map> joa = MqQueryCallService.GetMqMessage(MessageListBean);
			if (joa.size() == 0) {
				Thread.sleep(5000);
				joa = MqQueryCallService.GetMqMessage(MessageListBean);
			}
			joa.forEach(ele -> {
				Logger.debug(ele.toString());
			});
			// 查询自动导入的商品的信息
			List<AgentProductPo> ap = ymtProductsIWapper.selectAgentProductByRootProductId(productId).stream()
					.filter(x -> x.getAction() == 0).filter(x -> x.getUserId() == agentUserId)
					.collect(Collectors.toList());
			Logger.debug("ap:" + FormatUtil.beanToGSONString(ap));
			Logger.verifyEquals(true, ap.get(0).getAutoMarkup(), "验证isAutoMarkup");
			updatemarkupconfigBean.setAgentId(agentUserId);
			updatemarkupconfigBean.setOperateType(2);
			updatemarkupconfigBean.setSupplierId(rootUserId);
			updatemarkupconfigCall.setData(updatemarkupconfigBean);
			updatemarkupconfigCall.callService();
			Logger.verifyEquals("ok", updatemarkupconfigCall.getReturnData(), "验证code");
			Thread.sleep(2000);
			
			ap = ymtProductsIWapper.selectAgentProductByRootProductId(productId).stream()
					.filter(x -> x.getAction() == 0).filter(x -> x.getUserId() == agentUserId)
					.collect(Collectors.toList());
			Logger.debug("ap:" + FormatUtil.beanToGSONString(ap));
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

}